package middlewares

import (
	"strings"
	"time"

	"gitee.com/xgotool/backend-framework-template/config"
	"gitee.com/xiaoyutab/xgotool/xstring"
	"github.com/gin-gonic/gin"
)

// 提取用户的token信息
func UserInfo(c *gin.Context) {
	// 获取请求header中的token信息
	token := c.GetHeader("Authorization")
	if token != "" {
		// 验证token是否有效
		// 解密token信息
		info := struct {
			Id        uint   `json:"id"`       // 用户ID
			UserName  string `json:"username"` // 用户名
			Sign      string `json:"sign"`     // 签名
			CreatedAt int64  `json:"iat"`      // 创建时间
		}{}
		if strings.Contains(token, " ") {
			token = strings.Split(token, " ")[1]
		}
		c.Set("uid", uint(0))
		err := xstring.UnJwt([]byte(config.GetExt().JWT.Key), token, &info)
		if err == nil {
			// 验证签名是否正确
			if info.Sign == xstring.MD5(xstring.AString(info.UserName) + config.GetExt().JWT.Sign)[:6] {
				// 验证是否过期
				if config.GetExt().JWT.KeyExpired == 0 || info.CreatedAt+config.GetExt().JWT.KeyExpired > time.Now().Unix() {
					c.Set("uid", info.Id)
				}
			}
		}
		c.Next()
	}
}
